<?php

namespace Kangcg\Application\Validate\Rules;


use Kangcg\Application\Validate\Validator;

class Url implements RuleInterface
{
    use RuleTrait;

    public $https;

    protected function afterRun(&$value, string $field, array $input, Validator $validator)
    {
        if(filter_var($value, FILTER_VALIDATE_URL) === false){
            return $validator->setError($this->getMessage($field));
        }


        if(is_bool($this->https)){
            $parsedUrl = parse_url($value);
            $isHttps = (!empty($parsedUrl['scheme']) && $parsedUrl['scheme'] == 'https');
            if($this->https === true && !$isHttps){
                return $validator->setError($this->getMessage($field, '', ':attributes 不是有效的HTTPS路由'));
            }

            if($this->https === false && $isHttps){
                return $validator->setError($this->getMessage($field, '', ':attributes 不是有效的HTTP路由'));
            }
        }
    }
}
